package com.dreamana.ui
{
	import com.dreamana.command.BaseCommand;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	public class SkinLoadCommand extends BaseCommand
	{
		private var _url:String;
		private var _loader:Loader;
		
		public function SkinLoadCommand(url:String)
		{
			_url = url;
			_loader = new Loader();
		}
		
		override public function execute():void
		{
			this.registerListeners(_loader.contentLoaderInfo);
			_loader.load(new URLRequest(_url)); 
		}
		
		private function registerListeners(dispatcher:IEventDispatcher):void
		{
			dispatcher.addEventListener(Event.COMPLETE, onLoadComplete);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
		
		private function unregisterListeners(dispatcher:IEventDispatcher):void
		{
			dispatcher.removeEventListener(Event.COMPLETE, onLoadComplete);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
			
		//--- EVENT HANDLERS ---
		
		private function onLoadComplete(e:Event):void
		{
			this.unregisterListeners(_loader.contentLoaderInfo);
			
			//complete
			this.complete();
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			this.unregisterListeners(_loader.contentLoaderInfo);
			
			trace(e.text);
			
			//complete
			this.complete();
		}
		
		//--- GETTER/SETTERS ---
		public function set url(value:String):void { _url = value; }
		public function get url():String { return _url; }
		
		public function get loader():Loader { return _loader; }
	}
}